package syscompat

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"gopkg.openfuyao.cn/bkeadm/utils/log"
)

func SetSysctl() {
	file, err := os.OpenFile("/etc/sysctl.conf", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.BKEFormat(log.WARN, fmt.Sprintf("Unable to open file %s %s", "/etc/sysctl.conf", err.Error()))
		return
	} else {
		defer file.Close()
		sysconf, _ := os.ReadFile("/etc/sysctl.conf")
		if !strings.Contains(string(sysconf), "fs.file-max") {
			_, _ = file.WriteString("fs.file-max = 9000000\n")
		}
		if !strings.Contains(string(sysconf), "fs.inotify.max_user_watches") {
			_, _ = file.WriteString("fs.inotify.max_user_watches = 1000000\n")
		}
		if !strings.Contains(string(sysconf), "fs.inotify.max_user_instances") {
			_, _ = file.WriteString("fs.inotify.max_user_instances = 1000000\n")
		}
		if !strings.Contains(string(sysconf), "net.ipv4.ip_forward") {
			_, _ = file.WriteString("net.ipv4.ip_forward = 1\n")
		}
		err = exec.Command("sudo", "sysctl", "-p").Run()
		if err != nil {
			log.BKEFormat(log.WARN, fmt.Sprintf("Unable to set sysctl %s", err.Error()))
			return
		}
	}
}
